import { PdfJs, Store, StoreHandler } from "../../core";

import StoreProps from "./types/StoreProps";
import { useEffect, useState } from "react";

const useDocument = (
  store: Store<StoreProps>
): { currentDoc: PdfJs.PdfDocument } => {
  const [currentDoc, setCurrentDoc] = useState(store.get("doc"));

  const handleDocumentChanged: StoreHandler<PdfJs.PdfDocument> = (
    doc: PdfJs.PdfDocument
  ) => {
    setCurrentDoc(doc);
  };

  useEffect(() => {
    store.subscribe("doc", handleDocumentChanged);

    return () => {
      store.unsubscribe("doc", handleDocumentChanged);
    };
  }, []);

  return { currentDoc };
};

export default useDocument;
